
import numpy as np
import sys
import json
import sklearn.cluster as skc
import cv2

def doAnalysis(filename, errorRange):
    file = open(filename, encoding='utf-8')
    jsonset = json.load(file)
    dataset = []
    for i in range(len(jsonset)):
        data = []
        data.append(jsonset[i]["longitude"])
        data.append(jsonset[i]["latitude"])
        dataset.append(data)
    dataset = np.array(dataset, dtype=np.float32)
    # 将点进行聚类
    db = skc.DBSCAN(eps=float(errorRange) / 100000, min_samples=5).fit(dataset)
    core_samples_mask = np.zeros_like(db.labels_, dtype=bool)  # 设置一个样本个数长度的全false向量
    core_samples_mask[db.core_sample_indices_] = True #将核心样本部分设置为true
    labels = db.labels_
    unique_labels = set(labels)

    # 获取所有聚类的边界值
    area_list = []
    for k in zip(unique_labels):
        class_member_mask = (labels == k)  # 将所有属于该聚类的样本位置置为true
        xy = dataset[class_member_mask & core_samples_mask]  # 将所有属于该类的核心样本取出，使用大图标绘制
        if len(xy) == 0:
            continue

        # 获取轮廓的外切矩形
        sorted_x = sorted(xy[:,0:1])
        sorted_y = sorted(xy[:,1:2])
        x = sorted_x[0][0]
        y = sorted_y[0][0]
        w = sorted_x[-1][0] - sorted_x[0][0]
        h = sorted_y[-1][0] - sorted_y[0][0]

        # cv2.convexHull(xy)
        area_points = []

        leftBottom = {'longitude': x, 'latitude':y}
        leftTop =  {'longitude': x, 'latitude':y + h}
        rightTop =  {'longitude': x + w, 'latitude':y + h}
        rightBottom =  {'longitude': x + w, 'latitude':y}

        area_points.append(leftBottom)
        area_points.append(leftTop)
        area_points.append(rightTop)
        area_points.append(rightBottom)
        # 补上第一个点，使之能形成闭环
        area_points.append(leftBottom)

        area = {
            'points' : area_points,
            'alarmCount' : len(xy)
        }

        area_list.append(area)

    return area_list

if __name__ == '__main__':
    filename = sys.argv[1]
    errorRange = sys.argv[2]
    area_list = doAnalysis(filename, errorRange)
    np.set_printoptions(threshold=sys.maxsize)
    print(area_list)